/*
 * Copyright 2013-2018 Lilinfeng.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phei.netty.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author lilinfeng
 * @date 2014年2月16日
 * @version 1.0
 */
public class AcceptCompletionHandler implements
	CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> {

	/**
	 *
	 * @param result  :  触发ACCEPT事件的channel
	 * @param attachment: 携带server实例，用户关联新的事件
	 */
    @Override
    public void completed(AsynchronousSocketChannel result,
	    AsyncTimeServerHandler attachment) {
    	// 继续监听accept事件，死循环，这样就会一直监听accept事件下去
		attachment.asynchronousServerSocketChannel.accept(attachment, this);
		// 如果数组设置太小，需要循环调用异步read
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		// 把数据读取到buffer中，并且将buffer,做为ReadCompletionHandler.completed方法的回调入参
		// 异步io写操作，关联READ事件
		// buffer缓冲数组被填满就会 投递READ事件，所以当buffer比设置被tcp缓冲区小的时候，需要多次read
		// 所应用层在传输数据之前，应该线交流数据的长度。从而，接收方知道何时数据已接收完成，停止调用read.
		result.read(buffer, buffer, new ReadCompletionHandler(result));
    }

    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
		exc.printStackTrace();
		// 失败，结束主线程
		attachment.latch.countDown();
    }

}
